from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver, Service
from selenium.webdriver.common.by import By
import platform
import getpass
import random
import time

system = platform.system()
if system.startswith('Windows'):
    EXEC_DIR_PATH = f'C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/Application/chrome.exe'
    USER_DIR_PATH = f'C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/User_Data'
elif system.startswith('Apple'):
    EXEC_DIR_PATH = f'/Users/{getpass.getuser()}/Library/Application Support/Google/Chrome/Application/chrome'
    USER_DIR_PATH = f'/Users/{getpass.getuser()}/Library/Application Support/Google/Chrome/User_Data'
elif system.startswith('Linux'):
    EXEC_DIR_PATH = f'/home/{getpass.getuser()}/AppData/Local/Google/Chrome/Application/chrome'
    USER_DIR_PATH = f'/home/{getpass.getuser()}/AppData/Local/Google/Chrome/User_Data'


def get_browser_1() -> WebDriver:
    # 浏览器配置对象
    options = webdriver.ChromeOptions()
    # 禁用自动化栏
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    # 屏蔽保存密码提示框
    options.add_experimental_option('prefs', {
        'credentials_enable_service': False,
        'profile.password_manager_enabled': False
    })
    # 窗口最大化
    # options.add_argument("--start-maximized")
    # 无界面运行(无窗口), 也叫无头浏览器
    # options.add_argument("--headless")
    # 禁用GPU，防止无头模式出现莫名的bug
    # options.add_argument("--disable-gpu")
    # 禁用启用Blink运行时
    options.add_argument('--disable-blink-features=AutomationControlled')
    # 使用本地浏览器用户数据
    options.add_argument("--user-data-dir=" + USER_DIR_PATH)
    # options.binary_location = EXEC_DIR_PATH
    # service
    driver_path = f'F:\Projects Dev\python\demo2\chromedriver.exe'
    service = Service(executable_path=driver_path)
    driver = webdriver.Chrome(options=options, service=service)
    # 待执行的 JS 代码,修改 window.navigator.webdriver 的值
    # js_exec = 'Object.defineProperties(navigator,{webdriver:{get:() => undefined}});'
    # 移除selenium当中爬虫的特征
    # driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', '{"source", '+ js_exec +'}')
    # driver.implicitly_wait(10)
    return driver


def get_browser_2():
    import subprocess
    import time
    '''
    --remote-debugging-port=9999 是指定运行端口，只要没被占用就行
    --user-data-dir 指定运行浏览器的运行数据，新建一个干净目录，不影响系统原来的 数据
    --incognito 隐私模式打开
    --start-maximized 窗口最大化
    --new-window 直接打开网址
    '''
    # 启动命令
    command = f'{EXEC_DIR_PATH} --remote-debugging-port=9999 --remote-allow-origins=* --start-maximized'
    subprocess.Popen(command, shell=True)
    time.sleep(1)
    # 浏览器配置对象
    options = webdriver.ChromeOptions()
    options.debugger_address = 'localhost:9999'
    driver = webdriver.Chrome(options=options)
    return driver


def close_browser(browser: WebDriver):
    print('退出程序')
    # browser.close()
    browser.quit()


# 随机打开内容item
def random_click(page: WebDriver, info_list: [], css_selector: str=None, limit: int=3):
    count = 0
    origin_page = page.current_window_handle
    while count < limit and count < len(info_list):
        count = count + 1
        idx = random.randint(0, len(info_list) - 1)
        # 鼠标移动到对应元素
        # webdriver.ActionChains(page).move_to_element(info_list[idx]).perform()
        # 获取a标签链接
        href = info_list[idx].get_attribute('href')
        page.execute_script(f'window.open("{href}", "_blank");')
        # 暂停3秒
        time.sleep(3)
        # 新标签页
        window_handles = page.window_handles
        current_page = window_handles[-1]
        # 切换标签页
        page.switch_to.window(current_page)
        # 执行回调函数
        if css_selector is not None:
            info_items = page.find_elements(By.CSS_SELECTOR, css_selector)
            random_click(page, info_items, None, limit)
        # 关闭标签页
        page.close()
        page.switch_to.window(origin_page)

